<?php

class Create_files {
	private $host;
	private $user;
	private $passwd;
	private $encode;
	private $dbName;
	private $conn;

	// 构造函数
	public function __construct($dbName) {
		$this->host =  "127.0.0.1";
		//$this->host =  "115.29.136.117";
		$this->user =  "root";
		$this->passwd =  'fan1989115';
		$this->encode =  "UTF8";
		$this->dbName = $dbName;

		self::getConn($dbName);

//	$conn = $this->conn;
//
//		// 全部生成
//		$rs = mysqli_query($conn,"show tables");
//		if (!$rs){
//			echo "can't find the database or table";
//			return ;
//	}
//	while ( $arr_item = mysqli_fetch_assoc ( $rs ) ) {
//		$this->getFiles($arr_item['Tables_in_car_park_main']);
//		}

	}

	// 获取数据库连接
	public function getConn($db_name) {
		try {
			// 连接到Mysql
			$db = mysqli_connect ( $this->host, $this->user, $this->passwd );
			// 连接到数据库
			mysqli_query ( $db, "set names " . $this->encode );
			mysqli_select_db ( $db, $db_name );
			$this->conn = $db;
			return  $db;
		} catch ( Exception $e ) {
			throw $e;
		}
	}

	public function getFiles($tableName) {
		$array = array();
		$typeArr = array();

		$conn = $this->conn;

		$rs = mysqli_query($conn,"desc $tableName");
		if (!$rs){
			echo "can't find the database or table";
			return ;
		}

		$pre_key = "";
		$pre_key_fun_get = "";
		$pre_key_fun_set = "";
		while ( $arr_item = mysqli_fetch_assoc ( $rs ) ) {
			$typeArr[] = $arr_item['Type'];
			$array[] = $arr_item['Field'];
			if ($arr_item['Key'] == "PRI"){
				$pre_key = $arr_item['Field'];
				$pre_key_fun_get = "get" . ucfirst (  $pre_key );
				$pre_key_fun_set = "set" . ucfirst ( $pre_key  );
			}
		}

		//$className = strtolower($tableName);
		$className = ucfirst($tableName);
		$data_name = '../Data/temp/' . ( $className ) . '.php';
		$DAO_name = '../Data/temp/' . ( $className ) . '_DAO.php';

		$dataFile = fopen ( $data_name, 'w+' );
		$DAOFile = fopen ( $DAO_name, 'w+' );

		// 大写变量，小写变量,set,get对
		$variable_upper = array ();
		$variable_lower = array ();
		$variable_fun_set = array ();
		$variable_fun_get = array ();

		for($i = 0; $i < count ( $array ); $i ++) {
			// $variable_upper2 [$i] = strtoupper ( $array [$i + 1] );
			$variable_upper [$i] = $array [$i];
			$variable_lower [$i] =  $array [$i] ;
			$variable_fun_set [$i] = "set" . ucfirst ( $variable_lower [$i] );
			$variable_fun_get [$i] = "get" . ucfirst ( $variable_lower [$i] );
		}

		$fun_set = array ();
		$fun_get = array ();
		$def = '';
		$def.= "define('". ucfirst($className) ."','".($className)."');
			";
		for($i = 0; $i < count ( $array ); $i ++) {

			$def.= "define('". ucfirst($array[$i]) ."','".($array[$i])."');
			";

			$fun_set [$i] = 'public function ' . $variable_fun_set [$i] . '($value) {
			       $this->array = array_merge ($this->array,array(
			       ' . "'" . $array [$i] . "' " . '=> $value));
		     	} ';
			$fun_get [$i] = 'public function ' . $variable_fun_get [$i] . '(){

			      return $this->array [' . "'" . $array [$i] . "'" . '];
	            } ';
		}
		//字段


		// 构造函数
		$constructor = 'public function __construct ($array){

						$this->array = $array;

						 self::setDefault();

			   }

			          public function getArray() {
        					return $this->array;
   					 }

   					 	public function updateWithArray($array) {
		foreach($array as $key=>$value)
		{
			if(array_key_exists($key,$this->array))
			{
				$this->array = array_merge($this->array,array($key=>$value));
			}
		}
		}
			   ';

		// setDefault（）函数
		$setDefault = 'private function setDefault(){

						 if(count($this->array)==0){
				';
		for($i = 0; $i < count ( $array ); $i ++) {
			if($i == 0) {
				$setDefault .= 'self::' . $variable_fun_set [$i] . '("null");
					';
			} else {
				if(strstr( $typeArr[$i],'int') || strstr($typeArr[$i],'double') || strstr($typeArr[$i],'decimal'))
				{
					$setDefault .= 'self::' . $variable_fun_set [$i] . '("0");
					';
				} else {
					$setDefault .= 'self::' . $variable_fun_set [$i] . '("");
					';
				}
			}
		}
		$setDefault .= '
							}
					}
				';

		// toInsertCSV()函数
		$toInserCSV = 'public function toInsertCSV() {
						 $str="";
				';
		for($i = 0; $i < count ( $array ); $i ++) {

			if ( ( $array [$i] == 'CREATED_ON') || ( $array [$i] == 'UPDATED_ON')) {
				$toInserCSV .= '
						// ' . $variable_lower [$i] . '
						$str .= "now()" . ",";
						';
			} else {
				if ($i == (count($array)-1)){
					$toInserCSV .= '
						// ' . $variable_lower [$i] . '
						$str .= "\'". self::' . $variable_fun_get [$i] . '()."\'";';
				} else {
					if($i == 0) {
						$toInserCSV .= '
						// ' . $variable_lower [$i] . '
						$str .= self::' . $variable_fun_get [$i] . '().",";';
					} else {
						$toInserCSV .= '
						// ' . $variable_lower [$i] . '
						$str .= "\'". self::' . $variable_fun_get [$i] . '()."\',";';
					}
				}
			}
		}
		$toInserCSV .= '
						return $str;
						}
				';

		// toUpdateSet()函数
		$toUPdateSet = 'public function toUpdateSet() {
						 $str="";
				';
		for($i = 1; $i < count ( $array ); $i ++) {
			if (($array [$i] == 'UPDATED_ON')) {
				$toUPdateSet .= '
						// ' . $variable_lower [$i] . '
						$str .= "' . $variable_upper [$i] . ' = now()," ;
						';
			} else {
				if ($i == (count($array)-1)){
					$toUPdateSet .= '
						// ' . $variable_lower [$i] . '
						$str'.".= '`" . $variable_upper [$i] . "` = \"' . self::" . $variable_fun_get [$i] . "(). '\"';
						";
				} else {
					$toUPdateSet .= '
						// ' . $variable_lower [$i] . '
						$str'.".= '`" . $variable_upper [$i] . "` = \"' . self::" . $variable_fun_get [$i] . "() . '\",';
						";
				}
			}
		}
		$toUPdateSet .= 'return $str;
			    }
				';

		// toUpdateWhere() 函数
		$toUPdateWhere = 'public function toUpdateWhere(){
						 $str = "";
						$str .= "`' . $pre_key . '` = \'" . self::' . $pre_key_fun_get . '()."\'";
						 return $str;
		        }
		';

		// getRecord函数
		$getRecord = 'public static function getRecord($'.$pre_key.'){
						 $where = "`' . $pre_key . '` = \'$'.$pre_key.'\'' . '";
						 		 $record = self::query(\'select * from \'.static::$TABLENAME .\' where \'.$where);
								 if($record != null){
								 return new ' . $className . '($record[0]);
				      		}
				      		 return null;
				      		 }
		';

		// getList函数
		$getList = 'public static function getList() {
						 $where = "";
        				 $list = self::query(\'select * from \'.static::$TABLENAME);
						 $results = array();

						foreach($list as $record){
						  $results[] = new ' . $className . '($record);
								}
								 return $results;
	               }
';


		if ($pre_key != ""){
			// insert函数
			//有主键
			$insert = 'public static function insert($record){

						try {

								$'.$pre_key.' = $record->' .  $pre_key_fun_get . '();
								$oldrecord = self::getRecord($'.$pre_key.');
								if($oldrecord != null) {
								   throw new MyException ("重复插入");
								}
								$sql = \'insert into \'.static::$TABLENAME .\' values (\'.$record->toInsertCSV().\')\' ;
            					self::query($sql);
            					return self::$_db->lastInsertId();
							} catch(MyException $e){
								throw $e;
								}
						}
';
		}else{
			// insert函数
			//无主键
			$insert = 'public static function insert($record){
						try {
								$sql = \'insert into \'.static::$TABLENAME .\' values \'.$record->toInsertCSV();
            					self::query($sql);
							} catch(MyException $e){
								throw $e;
								}
						}
';
		}

		// update函数
		$update = 'public static function update($record){
						try{
								$'.$pre_key.' = $record->' . $pre_key_fun_get . '();
								$where = "`' . $pre_key . '` = \'$'.$pre_key.'\'' . '";
								$oldrecord = self::getRecord($'.$pre_key.');
								if($oldrecord == null){
										throw new MyException("不存在该记录");
								}
            					$sql = \'update \'.static::$TABLENAME .\' set \'.$record->toUpdateSet().\' where \'.$where ;
            					self::query($sql);
						} catch(MyException $e){
										throw $e;
									}
					 }
';

		// delete函数
		$delete = 'public static function delete ($record){
						try{
							$'.$pre_key.' = $record->' . $pre_key_fun_get . '();
							$where = "`' . $pre_key . '` = \'$'.$pre_key.'\'' . '";
							$oldrecord = self::getRecord($'.$pre_key.');
							if($oldrecord == null){
									throw new MyException("不存在该记录");
							}
            				$sql = \'delete from \'.static::$TABLENAME . \' where \'.$where ;
            				self::query($sql);
            				} catch(MyException $e){
									throw $e;
				        	}
					}
';

		// CLASS BEAN(基础类)
		$class_bean = 'class ' . $className . ' {

		    //数组
			private $array;


			' . $constructor . '


			' . $setDefault . '


			';

		for($i = 0; $i < count ( $array ); $i ++) {
			$class_bean .= '


			' . $fun_set [$i] . '
			' . $fun_get [$i];
		}


		if ($pre_key != ""){
			$class_bean .= '


			' . $toInserCSV . '


			' . $toUPdateSet . '


			' . $toUPdateWhere . "
}";
		}else{
			$class_bean .= '

			' . $toInserCSV . "
}";
		}



		// CLASS DAO (数据库操作类)
		$class_dao = 'class ' . $className . '_DAO {

						public static $TABLENAME = ' . "'" . ( $className ) . "'" . ';

							public static $_db;

	public static function query($str)
	{
		if(self::$_db === null) {
			self::$_db = \GatewayWorker\Lib\Db::instance(\'main\');
			return self::$_db->query($str);
		} else {
			return self::$_db->query($str);
		}
	}

								';


		if ($pre_key != ""){
			$class_dao .= '


				' . $getRecord . '


				' . $getList . '


			   ' . $insert . '


			   ' . $update . '


			   ' . $delete . '}';
		}else{
			$class_dao .= '

				' . $getList . '

			   ' . $insert . '}';
		}

		// 生成文件信心
		$file_php_info = '<?php
/**
 * 注：此模板为自动生成模板，需要根据实际情况调整修改
 * 此模板对 无主键/单一主键 表的支持较好，联合主键表在下一版本开发
 */
 namespace Data;

use Utils\MyException;

' . $class_bean . '

'.'// -----  数据库表: '.$className.'  -----

'.$def .'

?>';
		$file_php_info_DAO = '<?php
/**
 * 注：此模板为自动生成模板，需要根据实际情况调整修改
 * 此模板对 无主键/单一主键 表的支持较好，联合主键表在下一版本开发
 */
namespace Data;

use Utils\MyException;

' . $class_dao . '

?>';


		fputs ( $dataFile, $file_php_info );
		fclose ( $dataFile );

		fputs ( $DAOFile, $file_php_info_DAO );
		fclose ( $DAOFile );
	}

}

//**********************生成表************************************
$createFile = new Create_files('restaurant_order_main');
<<<<<<< HEAD
$createFile->getFiles('gonging_entry_order_form');
$createFile->getFiles('restaurant_withdraws');
$createFile->getFiles('account_flow');
=======
$createFile->getFiles('order_for_foods');
$createFile->getFiles('order_form');
>>>>>>> d1249ab11a0c4dafedf12a481164cd998b750588


echo "ok~";

